package com.zzh.rabbit;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.zzh.lib.core.utils.HMediaUtils;
import com.zzh.lib.core.utils.LogUtils;
import com.zzh.mvvm.base.BaseRabbitActivity;
import com.zzh.mvvm.binding.BindingAction;
import com.zzh.mvvm.binding.BindingConsumer;
import com.zzh.mvvm.bus.Messenger;
import com.zzh.mvvm.bus.RxBus;
import com.zzh.rabbit.databinding.ActivityMainBinding;
import com.zzh.rabbit.wifi.WifiActivity;

import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends BaseRabbitActivity<MainViewModel, ActivityMainBinding> {

    Disposable taskTimeout;

    @Override
    protected void initViewAndData(Bundle savedInstanceState) {
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            LogUtils.e("--------NAME: " + Thread.currentThread().getName());
        }, 100);

        Messenger.getDefault().register(this, new BindingAction() {
            @Override
            public void call() {

                Log.e("-----", "---------收到发出的消息");
            }
        });

        Messenger.getDefault().register(viewModel, User.class, new BindingConsumer<User>() {
            @Override
            public void call(User user) {
                if (user != null) {
                    Log.e("-----", "---------收到发出的消息: " + user.name);
                } else {
                    Log.e("-----", "---------收到发出的消息 null ");
                }
            }
        });
        bind.btnStart.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("user", "测试张三李四");
            startActivity(SecondActivity.class, bundle);
        });

        bind.btnThree.setOnClickListener(v -> startActivity(new Intent(this, ThreeAct.class)));
        bind.btnTwo.setOnClickListener(v -> startActivity(new Intent(this, TwoAct.class)));
        bind.btnFour.setOnClickListener(v -> {
            //RxBus.doTaskPeriodic(1000, 1000);

        });
        bind.btnFive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startContainerActivity(FragSub.class.getCanonicalName());
            }
        });
        RxBus.doTaskDelay(() -> {
            LogUtils.e("延迟执行任务：" + Thread.currentThread().getName());
        }, 1000);
    }

    @Override
    public void setListener() {
        super.setListener();
        bind.mbScanWifi.setOnClickListener(v -> startActivity(WifiActivity.class));

        bind.btnBusIoMain.setOnClickListener(v -> {
            LogUtils.d("-----1: " + Thread.currentThread().getName());
            RxBus.doTask(new RxBus.OnTaskConsumer() {

                @Override
                public ObservableOnSubscribe createTaskSource() {

                    return emitter -> {
                        LogUtils.d("-----2: " + Thread.currentThread().getName());
                        emitter.onNext("执行完成");
                    };
                }

                @Override
                public Consumer createConsumer() {
                    return new Consumer() {
                        @Override
                        public void accept(Object o) throws Throwable {
                            LogUtils.d("-----3: " + Thread.currentThread().getName());
                        }
                    };
                }
            });
        });
        bind.btnBus.setOnClickListener(v -> {

            RxBus.doTask(new ObservableOnSubscribe<Object>() {
                @Override
                public void subscribe(ObservableEmitter<Object> emitter) throws Throwable {
                    //这里是子线程
                    Log.d("RxBus", "----1: " + Thread.currentThread().getName());
                    Thread.sleep(1000);
                    throw new NullPointerException("主动抛出异常");
                }
            }, new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Throwable {
                    Log.d("RxBus", "----2: " + Thread.currentThread().getName());
                    Log.d("RxBus", "----3: " + o.toString());
                }
            }, RxBus.DEFAULT_THROWABLE_CONSUMER, new Action() {
                @Override
                public void run() throws Throwable {
                    Log.d("RxBus", "----Action: ");
                }
            });

        });

        bind.btnBusTimeout.setOnClickListener(v -> {
            if (taskTimeout != null && !taskTimeout.isDisposed()) {
                taskTimeout.dispose();
                taskTimeout = null;
            }
            taskTimeout = RxBus.doTaskTimeout(new RxBus.OnTaskTimeoutConsumer<String>() {
                @Override
                public ObservableOnSubscribe<String> createTaskSource() {
                    return emitter -> {
                        //耗时操作
                        Thread.sleep(2000);
                        emitter.onNext("执行完成");
                    };
                }

                @Override
                public long initialTimeout() {
                    return 1;
                }

                @Override
                public void timeoutObserver(Observer<? super String> observer) {
                    super.timeoutObserver(observer);
                    Log.d("-----", "---------: 任务超时");
                    observer.onComplete();
                }

                @Override
                public Consumer<String> createConsumer() {
                    return s -> Log.d("-----", "---------: " + s);
                }
            });
        });

        bind.btnStartPer.setOnClickListener(v -> {
            XXPermissions.with(MainActivity.this).permission(
                    Permission.MANAGE_EXTERNAL_STORAGE).request(new OnPermissionCallback() {
                @Override
                public void onGranted(List<String> permissions, boolean allGranted) {
                    if (allGranted) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("application/pdf");
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(Intent.createChooser(intent, "选择PDF文件"), 1000);
                    }

                }
            });

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == RESULT_OK) {
            List<String> paths = HMediaUtils.obtainSingleDocuments(data);
            if (paths.isEmpty()) {
                LogUtils.e("为空");
            } else {
                LogUtils.e(paths.get(0));
            }

        }
    }

    @Override
    protected int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onDestroy() {
        Messenger.getDefault().unregister(this);
        super.onDestroy();
    }
}